package com.jy.app.lib.net;

import android.content.Context;
import android.text.TextUtils;

import com.alibaba.fastjson.TypeReference;
import com.loopj.android.http.AsyncHttpClient;
import com.jy.app.lib.bean.BaseEntity;
import com.jy.app.lib.bean.BaseResponse;
import com.jy.app.lib.bean.UploadFileResponse;
import com.jy.app.lib.utils.JsonUtil;

import java.io.File;
import java.io.IOException;


/**
 * 文件下载、上传时的异步处理类
 * y
 * Created by jan on 2016/4/20.
 */
public class FileHttpResponseHandler extends CommonHttpResponseHandler{

    private String fileName;
    private File mFile;
    private Context context;
    private boolean isDelete = true;

    public FileHttpResponseHandler(Context context) {
        this.context = context;
        this.mFile = getTemporaryFile(context);
    }

    public FileHttpResponseHandler(Context context,File file) {
        this(context);
        this.context = context;
        this.mFile = file;
    }

    public FileHttpResponseHandler(Context context,boolean isDelete,File file) {
        this(context);
        this.isDelete = isDelete;
        this.context = context;
        this.mFile = file;
    }


    protected File getTemporaryFile(Context context) {
        Utils.asserts(context != null, "Tried creating temporary file without having Context");
        try {
            return File.createTempFile("temp_", "_handled", context.getCacheDir());
        } catch (IOException e) {
            AsyncHttpClient.log.e("FileHttpResponseHandler", "Cannot create temporary file", e);
        }
        return null;
    }


    @Override
    protected void onSuccess(String responseString) {
        super.onSuccess(responseString);
        if (isDelete)
        if(mFile!=null&&mFile.exists()){
            mFile.delete();
        }
        if(!TextUtils.isEmpty(responseString)){
            BaseResponse res = null;
            try {
                res = JsonUtil.parseObject(responseString,new TypeReference<BaseResponse>(){});
            } catch (Exception e) {
                e.printStackTrace();
                onFailure(-1,e.getLocalizedMessage());
            }
             UploadFileResponse response = JsonUtil.parseObject(res.getData().toString(),UploadFileResponse.class);
            if(res!=null&&res.getCode()==0){
                onSuccess(response);
            }else {
                onFailure(res.getCode(),res.getMsg());
            }
        }else{
            onFailure(-1,"received empty data!");
        }
    }

    @Override
    public void onCancel() {
        super.onCancel();
    }

    protected void onSuccess(BaseEntity object){
    }

    @Override
    public void onFailure(int failCode, String failSource) {
    }

    public String getFileName() {
        return fileName;
    }

}
